package cn.da.shuai.cool.finance.service.impl;

import cn.da.shuai.cool.common.expection.CoolServiceException;
import cn.da.shuai.cool.finance.mapper.CoolBudgetAuditMapper;
import cn.da.shuai.cool.finance.model.CoolBudgetAudit;
import cn.da.shuai.cool.finance.service.ICoolBudgetAuditService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class CoolBudgetAuditServiceImpl extends ServiceImpl<CoolBudgetAuditMapper, CoolBudgetAudit> implements ICoolBudgetAuditService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void recordAudit(CoolBudgetAudit audit) {
        if (audit.getBudgetId() == null) {
            throw new CoolServiceException("预算ID不能为空");
        }

        if (audit.getAction() == null || audit.getAction().trim().isEmpty()) {
            throw new CoolServiceException("审计操作不能为空");
        }

        if (audit.getUserId() == null) {
            throw new CoolServiceException("用户ID不能为空");
        }

        // 设置操作时间为当前时间
        audit.setActionTime(LocalDateTime.now());

        this.save(audit);
    }

    @Override
    public List<CoolBudgetAudit> getBudgetAuditHistory(Long budgetId) {
        LambdaQueryWrapper<CoolBudgetAudit> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CoolBudgetAudit::getBudgetId, budgetId)
                .orderByDesc(CoolBudgetAudit::getActionTime);

        return this.list(queryWrapper);
    }

    @Override
    public List<CoolBudgetAudit> getAuditsByUser(Long userId) {
        LambdaQueryWrapper<CoolBudgetAudit> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CoolBudgetAudit::getUserId, userId)
                .orderByDesc(CoolBudgetAudit::getActionTime);

        return this.list(queryWrapper);
    }

    @Override
    public List<CoolBudgetAudit> getAuditsByDateRange(String startDate, String endDate) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDateTime start = LocalDate.parse(startDate, formatter).atStartOfDay();
        LocalDateTime end = LocalDate.parse(endDate, formatter).atTime(23, 59, 59);

        LambdaQueryWrapper<CoolBudgetAudit> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.between(CoolBudgetAudit::getActionTime, start, end)
                .orderByDesc(CoolBudgetAudit::getActionTime);

        return this.list(queryWrapper);
    }
}